<template>
    <div>
        <div class="top_option">
            <el-button @click="addBanner" type="primary">新增轮播图</el-button>
        </div>
        <el-table :data="tableData" stripe style="width: 100%" highlight-current-row
            :header-cell-style="{ background: '#def2fb', color: '#000' }" >
            <!-- <el-table-column align="center" prop="id" label="Id" /> -->
            <el-table-column align="center" prop="bannerName" label="轮播图名称" />
            <el-table-column align="center" prop="bannerImage" label="轮播图">
                <template #default="scope">
                    <el-image class="tableData_image" :src="scope.row.bannerImage"></el-image>
                </template>
            </el-table-column>
            <el-table-column align="center" prop="createtime" label="创建时间" :formatter="formatDate">
            </el-table-column>
            <el-table-column align="center" label="操作">
                <template #default="scope">
                    <div style="display: flex; align-items: center;justify-content: center;">
                        <el-button size="small" type="warning" @click="editBanner(scope.row.id)">编辑</el-button>
                        <el-button size="small" type="danger" @click="deleteBanner(scope.row.id)">删除</el-button>
                    </div>
                </template>
            </el-table-column>
        </el-table>
        <div>
            <el-dialog v-model="dialogVisible" :title="title" width="60%" :before-close="handleClose">
                <el-form ref="banner" :model="form" :rules="rules" @submit.native.prevent="onSubmit" label-width="120px">
                    <el-form-item label="轮播图名称" prop="bannerName">
                        <el-input maxlength="30" v-model="form.bannerName" />
                    </el-form-item>
                    <el-form-item label="轮播图" prop="bannerImage">
                        <el-upload :headers="headers" class="upload_image" :before-upload="beforeAvatarUpload"
                            :http-request="uploadImage" :show-file-list="false">
                            <el-image :src="form.bannerImage" v-if="form.bannerImage" class="bannerImage" />
                            <el-icon :size="35" color="#a8abb2" v-else>
                                <Plus />
                            </el-icon>
                        </el-upload>
                    </el-form-item>
                </el-form>
                <template #footer>
                    <span class="dialog-footer">
                        <el-button @click="dialogVisible = false">取消</el-button>
                        <el-button type="primary" @click="onSubmit">
                            确认
                        </el-button>
                    </span>
                </template>
            </el-dialog>
        </div>
    </div>
</template>

<script>
import { imageUpload, BannerAddApi, BannerListApi, BannerEditApi, BannerDetailApi, BannerDeleteApi } from '@/api/index'
export default {
    data() {
        return {
            tableData: [],
            dialogVisible: false,
            title: '',
            form: {
                bannerImage: '',
                bannerName: ''
            },
            headers: {
                Authorization: localStorage.getItem("token"),
            },
            rules: {
                bannerName: [
                    { required: true, message: "轮播图名称不能为空", trigger: "blur" },
                ],
                bannerImage: [{ required: true, message: "轮播图不能为空", trigger: "blur" }],
            },
        }
    },
    mounted() {
        this.getBannerList()
    },
    methods: {
        //日期格式化
        formatDate(value) {
            const date = new Date(value.createtime);
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, "0");
            const day = String(date.getDate()).padStart(2, "0");
            return `${year}-${month}-${day}`;
        },
        addBanner() {
            this.dialogVisible = true
            this.title = '添加轮播图'
            this.form={}
        },
        getBannerList() {
            BannerListApi().then(res => {
                console.log(res, 'bannerlist');
                if (res.data.code == 1) {
                    this.tableData = res.data.data
                } else {
                    this.$message.error(res.data.msg)
                }
            })
        },
        editBanner(id) {
            this.title = '修改轮播图'
            BannerDetailApi(id).then(res => {
                console.log(res);
                if (res.data.code == 1) {
                    this.form = res.data.data
                } else {
                    this.$message.error(res.data.msg)
                }
            })
            this.dialogVisible = true
        },
        handleClose(){
            this.$confirm("确认关闭吗?", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
            }).then(res=>{
                this.dialogVisible=false
            }).catch(err=>{
                console.log('用户点击了取消');
            })
        },
        deleteBanner(id) {
            //这里加一层modle判断确认是否删除
            this.$confirm("确认要删除这篇文章吗?", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
            })
                .then((err) => {
                    BannerDeleteApi({ id: id }).then((res) => {
                        console.log(res);
                        if (res.data.code == 1) {
                            this.$message({
                                type: "success",
                                message: res.data.msg,
                                duration: 1500,
                                onClose: () => {
                                    this.getBannerList();
                                },
                            });
                        } else {
                            this.$message({
                                type: "error",
                                message: res.data.msg,
                            });
                        }
                    });
                })
                .catch((err) => {
                    console.log(err);
                    console.log("用户点击了取消");
                });
        },
        onSubmit() {
            this.$refs.banner.validate((valid) => {
                if (valid) {
                    if (this.form.id) {
                        BannerEditApi(this.form).then(res => {
                            if (res.data.code == 1) {
                                this.$message({
                                    type: 'success',
                                    message: res.data.msg,
                                    duration: 1500,
                                    onClose: () => {
                                        this.dialogVisible = false
                                        this.form = {}
                                        this.getBannerList()
                                    }
                                })
                            } else {
                                this.$message({
                                    type: 'error',
                                    message: res.data.msg,
                                    duration: 1500,
                                    onClose: () => {
                                        this.dialogVisible = false
                                        this.form = {}
                                        this.getBannerList()
                                    }
                                })
                            }
                        })
                    } else {
                        BannerAddApi(this.form).then(res => {
                            if (res.data.code == 1) {
                                this.$message({
                                    type: 'success',
                                    message: res.data.msg,
                                    duration: 1500,
                                    onClose: () => {
                                        this.dialogVisible = false
                                        this.form = {}
                                        this.getBannerList()
                                    }
                                })
                            } else {
                                this.$message({
                                    type: 'error',
                                    message: res.data.msg,
                                    duration: 1500,
                                    onClose: () => {
                                        this.dialogVisible = false
                                        this.form = {}
                                        this.getBannerList()
                                    }
                                })
                            }
                        })
                    }
                }
            })
        },
        //参数必须是param，才能获取到内容
        uploadImage(param) {
            // 获取上传的文件名
            var file = param.file;
            //发送请求的参数格式为FormData
            const formData = new FormData();
            formData.append("file", file);
            // 调用param中的钩子函数处理各种情况，这样就可以用在组件中用钩子了。也可以用res.code==200来进行判断处理各种情况
            imageUpload(formData, param)
                .then((res) => {
                    if (res.data.code == 1) {
                        console.log(res);
                        this.form.bannerImage = res.data.data.path
                    }
                })
                .catch((err) => {
                    param.onError(err);
                });
        },
        beforeAvatarUpload(file) {
            console.log(file.type);
            // if (
            //   file.type != "image/jpeg" ||
            //   file.type != "image/png" ||
            //   file.type != "image/gif"
            // )
            //   return this.$message.error("上传头像图片只能是 JPG、PNG、GIF 格式!");
            if (file.size > 500000)
                return this.$message.error("上传头像图片大小不能超过 5mb!");
        },
    }
}
</script>

<style lang="scss" scoped>
.top_option {
    background-color: white;
    padding: 20px;
    margin-bottom: 20px;
}

.tableData_image {
    width: 180px;
    height: 100px;
}

.bannerImage {
    width: 200px;
    height: 200px;
}
</style>